package cn.sh.yhk.acl.jwt;

import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname Yhk
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/10/2 16:55
 * @Created by y6522
 */
@Slf4j
@Component
public class JwtTokenUtil {

    public static final String TOKEN_HEADER = "x-access-token"; //token请求头
    public static final String TOKEN_PREFIX = "Bearer";//token前缀
    private static final String ISSUER = "Yhk"; //发行方
    private static final String SUBJECT = "Yhk-Admin"; //签名主题
    private static final String AUDIENCE = "Yhk-VUE"; //接收方
    private static String ROLE_CLAIMS = "role"; //角色权限声明
    private static String key = "adminyhk"; //jwt加解密使用的密钥;
    private static int expiration = 60 * 60; //jwt过期时间 秒级别

    private static final String CLAIM_KEY_USERNAME = "username";//登录的用户号
    private static final String CLAIM_KEY_CREATED = "created";// jwt创建时间


    public static void main(String[] args) {
        String key = "aabb";
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzV29yZCI6IjY2Njg4OSIsIm5iZiI6MTYzNTE1MDI3NiwiZXhwIjoxNjM1MTUwODc2LCJ1c2VyTmFtZSI6InpoYW5nc2FuIiwiaWF0IjoxNjM1MTUwMjc2fQ.Cq2AHyrZ-Q7U7O5BBPdEIBrm7aDtjQh4ZDvtIcLzQvg";
        JWT jwt = JWTUtil.parseToken(token);

        boolean verifyKey = jwt.setKey(key.getBytes()).verify();
        System.out.println(verifyKey);

        boolean verifyTime = jwt.validate(0);
        System.out.println(verifyTime);
    }

    /**
     * 生成token的过期时间
     */
    private static Date generateExpirationDate() {
        //毫秒级
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 根据用户信息生成token
     */
    public static String generateToken(UserDetails userDetails) {
        DateTime now = DateTime.now();
        Map<String, Object> payload = new HashMap<String, Object>();
        //签发时间
        payload.put(JWTPayload.ISSUER, ISSUER);
        payload.put(JWTPayload.SUBJECT, SUBJECT);
        payload.put(JWTPayload.AUDIENCE, AUDIENCE);
        payload.put(JWTPayload.EXPIRES_AT, generateExpirationDate());
        payload.put(JWTPayload.NOT_BEFORE, now);
        //过期时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //生效时间
        payload.put(JWTPayload.JWT_ID, "yhk");
        payload.put("username", userDetails.getUsername());
        return JWTUtil.createToken(payload, key.getBytes());
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        return JWTUtil.verify(token, key.getBytes());
    }

    /**
     * 从token中获取JWT中的有效载荷
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            // 捕获过期异常
            log.info("token：" + token);
            log.info("token已经过期：" + e.getMessage());
            claims = e.getClaims();
        } catch (Exception e) {
            log.info("token：" + token);
            log.info("JWT格式验证失败：" + e.getMessage());
        }
        return claims;
    }

    /**
     * 从token中获取登录用户名
     */
    public static String getUserNameFromToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload("username").toString();
    }

    /**
     * 从token中获取过期时间
     */
    public static Date getExpiredDateFromToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return new Date(Long.parseLong(jwt.getPayload("exp").toString()) * 1000);
    }


    /**
     * 判断token是否已经失效
     */
    public static boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }
}
